import {
	useStore
} from '@/store/index';
import {
	showToast,
	showLoading,
	hideLoading
} from '@/utils/toast';
/**
 *  rsa加密
 * @param {*} imgs
 */
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
export function RSAencrypt(str) {

	const encryptor = new JSEncrypt()
	const publicKey =
		'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDnyo1CsYjdcL1Qrpt9Nm2NAvn5WgJOUFCevQyHf6z8zFMUpqrul3ZOsDaIxw9nfv52rToVsEK2JgRGlLSmCIuPpZwMjkjERNXNnZPqFM4dwLMQIb+P9wf/xX3kb5LtPj7gYHzXeFQI94qvOS+lPwgQbA+zmDx7tswGOLASKTRr3QIDAQABMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDnyo1CsYjdcL1Qrpt9Nm2NAvn5WgJOUFCevQyHf6z8zFMUpqrul3ZOsDaIxw9nfv52rToVsEK2JgRGlLSmCIuPpZwMjkjERNXNnZPqFM4dwLMQIb+P9wf/xX3kb5LtPj7gYHzXeFQI94qvOS+lPwgQbA+zmDx7tswGOLASKTRr3QIDAQAB'

	encryptor.setPublicKey(publicKey) // 设置公钥

	return encryptor.encrypt(str)
}

/**
 * 打开文件
 * @param {String} url 文件地址
 */
export function openDocument(url) {
	uni.downloadFile({
		url: url,
		success: function(res) {
			var filePath = res.tempFilePath;
			uni.openDocument({
				filePath: filePath,
				showMenu: true,
				success: function(res) {
					console.log('打开文档成功');
				}
			});
		}
	});
}

/**
 * 重定向到登录页
 */
export function redirectToLogin() {
	const store = useStore();
	// 清理缓存
	store.clearStorage();
	// 重定向到登录页
	uni.reLaunch({
		url: '/pages/login/index'
	});
}

/**
 * 身份证号脱敏
 * @param {String} idCardNo 身份证号码
 */
export function idCardNoMask(idCardNo) {
	if (!idCardNo) return;

	let s1 = idCardNo.slice(1, 3);
	let s2 = idCardNo.slice(3, 6);
	let s3 = idCardNo.slice(6, 14);
	let s4 = idCardNo.slice(14, -1);
	let result =
		idCardNo.replace(s1, '** ')
		.replace(s2, '*** ')
		.replace(s3, '******** ')
		.replace(s4, '*'.repeat(s4.length))

	return result;
	// 441 424 19920915 2619
}

/**
 * 银行卡号脱敏
 * @param {String} bankCardNo 银行卡号
 */
export function bankCardNoMask(bankCardNo) {
	if (!bankCardNo) return;

	let s1 = bankCardNo.slice(0, 3);
	let s2 = bankCardNo.slice(3, 7);
	let s3 = bankCardNo.slice(7, -4);
	let result =
		bankCardNo.replace(s1, '*** ')
		.replace(s2, '**** ')
		.replace(s3, '*'.repeat(s3.length) + ' ')

	return result;
}

/**
 * 手机号脱敏
 * @param {String} phone 银行卡号
 */
export function phoneMask(phone) {
	if (!phone) return;

	let s1 = phone.slice(3, 7);
	let result =
		phone.replace(s1, ' **** ')

	return result;
}

/**
 * 保存图片到相册
 * @param {String} url 图片资源路径
 */
export function saveImageToAlbum(url, type = 'network') {
	//验证用户是否授权可以访问相册
	uni.getSetting({
		success(res) {
			if (res.authSetting['scope.writePhotosAlbum']) {
				saveImage(url, type);
			} else {
				// 发起授权
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success() {
						saveImage(url, type);
					},
					fail() {
						// 引导用户授权
						uni.showModal({
							content: '请授权访问相册',
							success(res) {
								if (res.confirm) {
									uni.openSetting();
								}
							},
						});
					},
				});
			}
		},
	});
}

/**
 * 保存图片到相册
 * @param {String} url 图片资源路径
 */
export function saveImage(url, type) {
	showLoading('加载中');

	if (type === 'network') {
		uni.downloadFile({
			url, // 图片路径
			success: (res) => {
				if (res.statusCode === 200) {
					console.log('下载成功');

					// 保存图片
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success() {
							setTimeout(() => {
								showToast('图片已保存至相册', 'none');
							}, 0);
						},
						fail() {
							setTimeout(() => {
								showToast('保存失败，请稍后重试', 'none');
							}, 0);
						},
						complete() {
							hideLoading();
						},
					});
				}
			},
			fail: (err) => {
				showToast('保存失败，请稍后重试', 'none');
			}
		});
	} else {
		// 保存图片
		uni.saveImageToPhotosAlbum({
			filePath: url,
			success() {
				setTimeout(() => {
					showToast('图片已保存至相册', 'none');
				}, 0);
			},
			fail() {
				setTimeout(() => {
					showToast('保存失败，请稍后重试', 'none');
				}, 0);
			},
			complete() {
				hideLoading();
			},
		});
	}
}

/**
 * 数字格式化
 * @param decimal 小数位数
 * @param isZeroPadding 是否补0（取出小数点后面的0）
 */
export function digit(value, decimal = 2, isZeroPadding = true) {
	if (!value) {
		var zero = 0;
		return zero.toFixed(decimal);
	}
	var result = (+value).toFixed(decimal);
	if (!isZeroPadding) result = parseFloat(result);
	return result;
}

/**
 * 金额万位缩略显示
 * @param decimal 小数位数
 * @param isZeroPadding 是否补0（取出小数点后面的0）
 */
export function digitBreviary(value, decimal = 2, isZeroPadding = true) {
	if (!value || value === '0') {
		let zero = 0;
		zero = zero.toFixed(decimal);
		if (!isZeroPadding) zero = parseFloat(zero);
		return zero;
	} else if ((+value > 0 && +value < 10000) || (value < 0 && value > -10000)) {
		let result = (+value).toFixed(decimal);
		if (!isZeroPadding) result = parseFloat(result);
		return result;
	} else if (+value >= 10000 || value <= -10000) {
		let result = (Math.floor(+value / 100) / 100).toFixed(2) + '万';
		return result;
	}
}

/**
 * 检查区间数据是否正确填写
 * @param {Array} rules 需要检查的数据
 * @param {Object} obj 数据对象
 */
export function checkRange(rules, obj) {
	let i = 0
	const length = rules.length;

	while (i < length) {
		const {
			key,
			placeholder
		} = rules[i];
		const data = obj[key];

		if (data[0] && !data[1]) {
			showToast(`请输入${placeholder[1]}`);
			return false
		}

		if (!data[0] && data[1]) {
			showToast(`请输入${placeholder[0]}`);
			return false
		}

		if (Number(data[0]) > Number(data[1])) {
			showToast(`${placeholder[0]}不能大于${placeholder[1]}`);
			return false
		}

		i++
	}

	return true
}